<script lang="ts" setup>
import RoomStatus from './components/room-status.vue'
import RoomMessage from './components/room-message.vue'
import RoomAction from './components/room-action.vue'
import { ref, onMounted, onUnmounted, nextTick, provide } from 'vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType } from '@/enums'
import { getConsultOrderDetail } from '@/api/consult'
import type { ConsultOrderItem } from '@/types/consult'
import { OrderType } from '@/enums'
import type { Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'
const route = useRoute()
const store = useUserStore()

const consult = ref<ConsultOrderItem>()

// 消息列表
const list = ref<Message[]>([])
const initialMsg = ref(true)
// 记录一个socket，方便后面使用（发消息给服务器）
let socket: Socket
onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
  /**
   * 参数1：连接服务器的地址
   * 参数2：选项对象（授权、参数）
   */
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  // 连接成功
  socket.on('connect', () => {
    // console.log('---connect success---')
  })

  // 获取第一次进来的消息数据
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log('---data---', data)
    // arr就是某一页的数据
    const arr: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      // 往某一个页的最前面添加的一个时间消息
      arr.unshift({
        createTime: item.createTime,
        id: item.createTime,
        msg: {
          content: item.createTime
        },
        msgType: MsgType.Notify
      })

      arr.push(...item.items)
    })

    // 这里记住，我们将来加载更前的聊天记录，是往前面加的
    list.value.unshift(...arr)

    loading.value = false

    if (data.length === 0) {
      return showToast('没有更多聊天记录了')
    }

    if (initialMsg.value) {
      // 第一次加载消息（也就是最后一页消息的时候），滚动到底部
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight)
      })

      initialMsg.value = false
    }

    console.log('---list---', list.value)
  })

  // 后台状态发生了改变
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })

  // 接收到发送成功或是医生发送来的消息
  socket.on('receiveChatMsg', async event => {
    list.value.push(event)
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
  })

  // 连接失败
  socket.on('error', error => {
    console.log('---error---', error)
  })

  // 失去连接
  socket.on('disconnect', () => {
    console.log('---disconnect---')
  })
})

// 发送文本消息
const sendText = (content: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 发送人
    to: consult.value?.docInfo?.id, // 接收人
    msgType: MsgType.MsgText, // 消息类型
    msg: {
      content
    }
  })
}

// 发送图片消息
const sendImage = (picture: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 发送人
    to: consult.value?.docInfo?.id, // 接收人
    msgType: MsgType.MsgImage, // 消息类型
    msg: {
      picture
    }
  })
}

const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  /**
   * 参数1：事件名称
   * 参数2：多少条
   * 参数3：时间戳，加载该时间之前的聊天记录
   * 参数4：订单id
   */
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

onUnmounted(() => {
  socket && socket.close()
})

const changeEvaluateDoc = (score: number) => {
  const item = list.value.find(item => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msgType = MsgType.CardEva
    item.msg.evaluateDoc = { score }
  }
}

provide('consult', consult)
provide('changeEvaluateDoc', changeEvaluateDoc)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室"></cp-nav-bar>
    <RoomStatus :status="consult?.status" :countdown="consult?.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage :list="list" />
    </van-pull-refresh>
    <RoomAction
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
